/**
 * 
 */
package com.cqcis.uip.base.framework.service.impl;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cqcis.uip.base.framework.core.impl.ResetServiceManageImpl;
import com.cqcis.uip.base.framework.service.ResetService;

/**
 * @author huangmy
 * @date 2008-2-21
 */
public abstract class ResetServiceAdaptor implements ResetService {
	private static Log log = LogFactory.getLog(ResetServiceAdaptor.class);
	private long timeConfiguration;      /* 上一次重置时间 */
	private long timeToRegetConfiguartion;  /* 重置间隔时间 */
	private boolean reset;  
	private boolean first;  /* 是否第一次 */
	private String description; // 描述
		
	public String getDescription() {
		return this.description;
	}
	
	public void start() throws Exception {
		reset();
		ResetServiceManageImpl.getInstance().registerResetService(this);
	}
	
	public void stop() throws Exception {
		ResetServiceManageImpl.getInstance().removeResetService(this);
	}
		
	public synchronized boolean maybeReset() {
		if (canReset()) {
			try {
				reset();
			} catch (Exception e) {
				log.info("Reset MappingConfig Exception: ", e);
				
				canReset(true);
				
				return false;
			}
			
			return true;
		}
		
		return false;
	}
	
	private boolean canReset() {
		if (reset) {
			reset = false;
			return true;
		}
		
		if (first) {
			first = false;
			this.timeConfiguration = System.currentTimeMillis();
			return false;
		}
		
		if (System.currentTimeMillis() - this.timeConfiguration < timeToRegetConfiguartion) {
			return false;
		}
		
		return true;
	}
	
	private void canReset(boolean reset) {
		this.reset = reset;
	}
	
	public void reset() throws Exception {
		this.timeConfiguration = System.currentTimeMillis();
		
		doReset();
	}
	
	public long getLastResetTime() {		
		return this.timeConfiguration;
	}
	
	public long getTimeToRegetConf() {		
		return this.timeToRegetConfiguartion;
	}
	
	public Map<?, ?> getCache() {		
		return doGetCache();
	}
	
	/**
	 * 定制重置
	 * @throws Exception
	 */
	protected abstract void doReset() throws Exception;
	
	/**
	 * 缓冲区
	 * 
	 * @return
	 */
	protected abstract Map<?, ?> doGetCache();
	
	public void setTimeToRegetConfiguartion(long timeToRegetConfiguartion) {
		this.timeToRegetConfiguartion = timeToRegetConfiguartion;
	}

	public void setDescription(String description) {
		this.description = description;
	}
}
